package com.glink.gateway.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt工具类
 *
 * @author lzh
 * @since 2022-06-09 15:03
 */
public abstract class JwtUtil {
    /**
     * 设置过期时间,单位
     */
    public static final long EXPIRE_TIME_IN_SECOND = 480 * 60;

    /**
     * token秘钥
     */
    private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";

    /**
     * 用户登录用户
     */
    public static final String LOGIN_NAME = "loginName";
    /**
     * 随机串
     */
    public static final String RANDOM = "random";

    /**
     * 登录类型
     */
    public static final String LOGIN_TYPE = "loginType";

    /**
     * 认证的前缀
     */
    public static final String _BEARER = "Bearer";
    /**
     * 认证的Header项目
     */
    public static final String _AUTHORIZATION = "Authorization";

    /**
     * 生成token
     *
     * @return 返回生成的token
     */
    public static String generateToken(String username, String random) {
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        // 过期时间
        Date expireTime = new Date(System.currentTimeMillis() + EXPIRE_TIME_IN_SECOND * 1000);
        // 设置头部信息
        Map<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        return JWT
                .create()
                .withHeader(header)
                .withClaim(LOGIN_NAME, username)
                .withClaim(RANDOM, random)
                .withExpiresAt(expireTime)
                .sign(algorithm);
    }

    /**
     * 验证token
     *
     * @param token 需要验证的token字符串
     * @return 返回布尔数据
     */
    public static boolean verify(String token) {
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        return true;
    }

    /**
     * 解析toekn
     *
     * @param token 要被解析的toekn
     * @return 返回解析内容
     */
    public static Map<String, Claim> parseJWT(String token) {
        DecodedJWT decodedToken = JWT.decode(token);
        return decodedToken.getClaims();
    }

    public static boolean isJwtExpired(String token) {
        DecodedJWT decodedToken = JWT.decode(token);
        return decodedToken.getExpiresAt().before(new Date());
    }


//    /**
//     * 从Request中获得JWT token
//     *
//     * @return
//     */
//    public static String getJwtTokenFromRequest(HttpServletRequest request) {
//        String[] content = BaseCommonUtils.findCustomHeaderValue(_AUTHORIZATION);
//        if (Objects.nonNull(content) && content.length > 0) {
//            return StringUtils.trim(StringUtils.replace(content[0], _BEARER, ""));
//        } else {
//            return null;
//        }
//
//    }

    public static void main(String[] args) {
        String username = "zhangsan";
//      String token = generateToken(username, "abdafde");
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.9yJyYW5kb20iOiJhYmRhZmRlIiwibG9naW5OYW1lIjoiemhhbmdzYW4iLCJleHAiOjE2NzIyMzI0NjV9.BdokJDWCEbPpKrTB8_GJMh3nmEOve4fU4x4Hmsem1xg";
        boolean b = verify(token);
        Map<String, Claim> map = parseJWT(token);
        System.out.println("loginName" + map.getOrDefault(LOGIN_NAME, null).asString());
        System.out.println("random" + map.getOrDefault(RANDOM, null).asString());
        System.out.println(token);
        boolean a = isJwtExpired(token);
        System.out.println("是否已经过期----->: " + a);
        System.out.println(b);
    }
}
